#include "core.h"
#include <QDebug>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusMessage>
#include <QtDBus/QDBusInterface>
#include <QFile>

Core::Core(QObject *parent)
: QObject(parent),
  m_Step(0),
  m_OutgoingCallActive(false)
{
    QDBusConnection dbus = QDBusConnection::systemBus();

    dbus.disconnect( "com.nokia.csd.Call",
                     "/com/nokia/csd/call/1",
                     "com.nokia.csd.Call.Instance",
                     "CallStatus",
                     this,
                     SLOT( handleCallEstablished( const QDBusMessage& )) );
}

bool Core::initialize()
{
    QDBusConnection dbus = QDBusConnection::systemBus();

    if(!dbus.isConnected())
    {
        qDebug() << "unable to connect to DBus daemon";
        return false;
    }

    bool success = dbus.connect( "com.nokia.csd.Call",           //service
                                 "/com/nokia/csd/call/1",        //path
                                 "com.nokia.csd.Call.Instance",  //interface
                                 "CallStatus",                   //name
                                 this,
                                 SLOT( handleCallStatusChanged( const QDBusMessage& )) );

    if(!success)
    {
        qDebug() << "unable to connect to com.nokia.csd.Call";
        return false;
    }

    connect( &m_Timer, SIGNAL(timeout()), this, SLOT(timeout()));

    return true;
}

void Core::handleCallStatusChanged( const QDBusMessage& msg)
{
    QList<QVariant> args = msg.arguments();
    const int argsCount = args.size();

    bool vibra(false);
    if(argsCount)
    {
        int state1 = args[0].toInt();
        int state2 = args[1].toInt();
        int state3 = args[2].toInt();

        if( state1 == 1 &&
            state2 == 0 &&
            state3 == 0)
        {
            m_OutgoingCallActive = true;
        }
        else if( state1 == 0 &&
                 state2 == 1 &&
                 state3 == 3)
        {
            m_OutgoingCallActive = false;
        }

        if( state1 == 8 &&
            m_OutgoingCallActive)
        {
            vibra = true;
        }
    }

    if(vibra)
    {
        m_Timer.start(200);

        vibrate();
        m_Step = 1;
    }
}

void Core::vibrate()
{
    QFile file("/sys/dev/char/10:142/device/bus/devices/twl4030_vibra/pulse");
    if( file.open(QIODevice::WriteOnly))
    {
        if( file.write( "128 50\0", 7 ) == -1)
        {
            qDebug() << "unable to write data into vibra";
        }
        file.close();
    }
    else
    {
        qDebug() << "unable to open vibra device";
    }
}

void Core::timeout()
{
    if(m_Step == 3)
    {
        m_Timer.stop();
        return;
    }

    vibrate();

    m_Step++;
}
